<?php
/**
 * Created By base
 * Author: Virus
 * Date: 2020/3/31
 * Time: 16:56
 */

namespace app\admin\controller;


use app\admin\logic\IpLogic;
use think\App;
use think\Request;

class Ip extends Base
{
    protected $logic = null;

    public function __construct(App $app = null)
    {
        parent::__construct($app);
        $this->logic = new IpLogic();
    }

    /**
     * IP地址管理列表
     * @return \think\response\View
     */
    public function index()
    {
        try {
            $lists = $this->logic->getLists();
        } catch (\Exception $e) {
            return [];
        }

        return view('ip/index', compact('lists'));
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $data = input("post.");
            try {
                $res = $this->logic->addIp($data);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            if ($res) {
                $this->success("IP地址添加成功", url('Ip/index'));
            }
            $this->error("IP地址添加失败");
        } else {

            return view();
        }
    }

    public function edit()
    {
        if ($this->request->isPost()) {
            $id         = input("post.id");
            $updateData = [
                'ip_address' => input("post.ip_address", "", "trim"),
                'status'     => input('post.status', 0, 'intval'),
            ];
            try {
                $res = $this->logic->updateIp($id, $updateData);
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }

            if ($res) {
                $this->success("ip地址编辑成功", url('Ip/index'));
            }
            $this->error("ip地址编辑失败");
        } else {
            $id     = input("param.id", 0, "intval");
            $ip_one = $this->logic->getIpOneById($id);

            return view('ip/edit', compact('ip_one'));
        }
    }

    public function delete(Request $request)
    {
        if (!$request->isPost() || !$request->isAjax()) {
            return writeJson(0, "请求类型不合法");
        }

        $id = $request->post('id', 0, 'intval');
        try {
            $result = $this->logic->deleteById($id);
        } catch (\Exception $e) {
            return writeJson(0, $e->getMessage());
        }

        if ($result) {
            return writeJson(1, "ip删除成功");
        }

        return writeJson(0, "ip删除失败");
    }
}